using Microsoft.EntityFrameworkCore;
using PandaWebAPI.Models.ef;

namespace PandaWebAPI.Services
{
    public class OrderService : BaseService<Order>, IOrderService
    {
        public OrderService(PandaSystemContext context) : base(context)
        {
        }

        public async Task<List<Order>> GetOrdersByUserIdAsync(Guid userId)
        {
            return await _dbSet
                .Include(o => o.OrderItems)
                .Where(o => o.UserId == userId)
                .OrderByDescending(o => o.OrderDate)
                .ToListAsync();
        }

        public async Task<List<Order>> GetOrdersByStatusAsync(byte status)
        {
            return await _dbSet
                .Include(o => o.OrderItems)
                .Include(o => o.User)
                .Where(o => o.Status == status)
                .OrderByDescending(o => o.OrderDate)
                .ToListAsync();
        }

        public async Task<Order> UpdateOrderStatusAsync(Guid orderId, byte status)
        {
            var order = await _dbSet
                .Include(o => o.OrderItems)
                .FirstOrDefaultAsync(o => o.OrderId == orderId);

            if (order == null)
                throw new KeyNotFoundException($"Order with ID {orderId} not found.");

            order.Status = status;
            await _context.SaveChangesAsync();
            
            return order;
        }

        public async Task<Order> AddOrderItemAsync(Guid orderId, OrderItem item)
        {
            var order = await _dbSet
                .Include(o => o.OrderItems)
                .FirstOrDefaultAsync(o => o.OrderId == orderId);

            if (order == null)
                throw new KeyNotFoundException($"Order with ID {orderId} not found.");

            item.OrderItemId = Guid.NewGuid();
            order.OrderItems.Add(item);
            
            // 重新计算订单总金额
            order.TotalAmount = await CalculateOrderTotalAsync(orderId);
            
            await _context.SaveChangesAsync();
            return order;
        }

        public async Task<Order> RemoveOrderItemAsync(Guid orderId, Guid itemId)
        {
            var order = await _dbSet
                .Include(o => o.OrderItems)
                .FirstOrDefaultAsync(o => o.OrderId == orderId);

            if (order == null)
                throw new KeyNotFoundException($"Order with ID {orderId} not found.");

            var item = order.OrderItems.FirstOrDefault(i => i.OrderItemId == itemId);
            if (item == null)
                throw new KeyNotFoundException($"Order item with ID {itemId} not found.");

            order.OrderItems.Remove(item);
            
            // 重新计算订单总金额
            order.TotalAmount = await CalculateOrderTotalAsync(orderId);
            
            await _context.SaveChangesAsync();
            return order;
        }

        public async Task<decimal> CalculateOrderTotalAsync(Guid orderId)
        {
            var order = await _dbSet
                .Include(o => o.OrderItems)
                .FirstOrDefaultAsync(o => o.OrderId == orderId);

            if (order == null)
                throw new KeyNotFoundException($"Order with ID {orderId} not found.");

            return order.OrderItems.Sum(item => item.Quantity * item.UnitPrice);
        }

        public override async Task<Order> CreateAsync(Order order)
        {
            // 设置默认值
            order.OrderId = Guid.NewGuid();
            order.OrderDate = DateTime.UtcNow;
            order.Status = 0; // 待支付状态
            
            // 计算订单总金额
            order.TotalAmount = order.OrderItems.Sum(item => item.Quantity * item.UnitPrice);

            await _dbSet.AddAsync(order);
            await _context.SaveChangesAsync();
            
            return order;
        }

        public override async Task<Order> UpdateAsync(Order order)
        {
            var existingOrder = await _dbSet
                .Include(o => o.OrderItems)
                .FirstOrDefaultAsync(o => o.OrderId == order.OrderId);

            if (existingOrder == null)
                throw new KeyNotFoundException($"Order with ID {order.OrderId} not found.");

            // 只允许更新特定字段
            existingOrder.ShippingAddress = order.ShippingAddress;
            existingOrder.PaymentMethod = order.PaymentMethod;
            existingOrder.TransactionId = order.TransactionId;
            existingOrder.Status = order.Status;

            // 如果订单项有变化，重新计算总金额
            if (order.OrderItems != null && order.OrderItems.Any())
            {
                existingOrder.TotalAmount = order.OrderItems.Sum(item => item.Quantity * item.UnitPrice);
            }

            await _context.SaveChangesAsync();
            return existingOrder;
        }

        public override async Task<bool> DeleteAsync(Guid id)
        {
            var order = await _dbSet
                .Include(o => o.OrderItems)
                .FirstOrDefaultAsync(o => o.OrderId == id);

            if (order == null)
                return false;

            // 删除订单项
            _context.OrderItems.RemoveRange(order.OrderItems);
            
            // 删除订单
            _dbSet.Remove(order);
            await _context.SaveChangesAsync();
            
            return true;
        }
    }
} 